<template>

  <div>
    <el-dialog
      title="初始登录必须更改密码"
      :visible.sync="resetPasswordDialogVisible"
      width="30%"
    >
      <el-form>
        <el-form-item>
          密码规则:最短6位，最长16位 {6,16},包含小写大母 [a-z] 和大写字母 [A-Z] ,可以包含数字 [0-9]
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="password_1" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="password_2" />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
       <el-button
          type="primary"
          @click="resetPasswordDialogVisible=false"
        >取消</el-button>
        <el-button
          type="primary"
          @click="changePasswd"
        >确 定</el-button>
      </span>
    </el-dialog>
    <div class="loginbox">
      <div
        class="loginboxinner"
        style="margin-top:200px"
      >
        <div class="logo">
          <h2 class="logo">高等职业院校人才培养工作状态数据采集与管理系统 </h2>
          <span class="slogan">v2019 1.42</span>
        </div>
        <!--logo-->
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
        >
          <div class="username">
            <div class="usernameinner">
              <el-select
                style="width:100%"
                @focus="focusSchool"
                v-model="loginForm.XXID"
                filterable
                placeholder="输入学校关键字进行选择"
              >
                <el-option
                  v-for="item in schools"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="username">
            <div class="usernameinner">
              <el-input
                type="text"
                v-model="loginForm.username"
                name="username"
                id="username"
              />
            </div>
          </div>

          <div class="password">
            <div class="passwordinner">
              <el-input
                type="password"
                v-model="loginForm.password"
                name="password"
                id="password"
              />
            </div>
          </div>
          <div v-if="errorCount>0">
            <el-form-item prop="code">
              <el-row :span="24">
                <el-col :span="12">
                  <el-input
                    v-model="loginForm.code"
                    auto-complete="off"
                    placeholder="请输入验证码"
                    size=""
                    @keyup.enter.native="submitForm('loginForm')"
                  ></el-input>
                </el-col>
                <el-col :span="12">
                  <div
                    class="login-code"
                    @click="refreshCode"
                  >
                    <!--验证码组件-->
                    <SIdentify :identifyCode="identifyCode"></SIdentify>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
          <el-button
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleLogin"
          >
            登录
          </el-button>

        </el-form>
        <!--loginboxinner-->
      </div>

      <!-- <div id="robot"></div> -->
    </div>
  </div>
  <!--loginbox-->
</template>

<script>
import { uuid } from "vue-uuid";
import SIdentify from "@/components/Sidentify";
import { showLoading, hideLoading } from "@/utils/loading";
import { isvalidUsername } from "@/utils/validate";
import { setUser,getSchool,setSchool } from "../../utils/auth";
import {update权限} from "@/api/权限"
import { login, getSchoolList } from "@/api/login";
import { add登录日志 } from "@/api/权限";
import linq from "linq";

export default {
  name: "Login",
  components: { SIdentify },
  data() {
    const validateCode = (rule, value, callback) => {
      if (this.identifyCode !== value) {
        this.loginForm.code = "";
        this.refreshCode();
        callback(new Error("请输入正确的验证码"));
      } else {
        callback();
      }
    };
    return {
      resetPasswordDialogVisible:false,
      identifyCodes: "1234567890",
      errorCount: 0,
      identifyCode: "",
      schools: [],
      loginForm: {
        username: "",
        password: "",
        server: "",
        XXID: ""
      },
      loginRules: {
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { validator: validateCode, trigger: "blur" }
        ]
      },
      password_1:'',
      password_2:'',
      loading: false,
      pwdType: "password",
      redirect: undefined,
      ErrorCount: 0,
      widgetId: null,
      Robot: true
    };
  },
  watch: {
    "loginForm.XXID": function(val, old) {
      this.loginForm.server = linq
        .from(this.schools)
        .firstOrDefault(`$.value=='${val}'`);
    },
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
    // ErrorCount(val){

    //   if(val>=3 && this.Robot == true ){
    //     this.onloadCallback()
    //   }
    // }
  },
  async mounted() {
    this.errorCount = isNaN(parseInt(window.localStorage.getItem("errorCount")))
      ? 0
      : parseInt(window.localStorage.getItem("errorCount"));
    this.refreshCode();
    showLoading();
    var school = await getSchoolList("2019");
    
    var xxid = getSchool();
    if(xxid)
    this.loginForm.XXID =xxid;
    else
    this.loginForm.XXID="12572";
    
    hideLoading();
    this.schools = this.schools.concat(
      school.map(e => {
        return { value: e.UserCard, label: e.UserName, server: e._IPName };
      })
    );
  },
  methods: {
    refreshCode() {},
    focusSchool() {
      this.loginForm.XXID = getSchool()? getSchool():"";
    },
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },
  
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
        ];
      }
    },
    async changePasswd(){
      //
      
      if(this.password_1 !== this.password_2){
        this.$alert("二次密码必须一致")
        return;
      }
      if( /^[\w]{6,16}$/.test(this.password_1)==false){
        //
          this.$alert("密码不合符规则")
          return;
      }
      var user = this.$root.user;
      user.PASSWORD = this.password_1;
      delete user.SCHOOL;
      await update权限(user)
      this.resetPasswordDialogVisible=false;
      //
       var school = linq
                .from(this.schools)
                .firstOrDefault(`$.value =='${this.loginForm.XXID}' `);
        user.SCHOOL = school.label;
              setUser(user);
            
              await add登录日志({
                ID: uuid.v1(),
                LOGINTIME: new Date().toISOString(),
                GH: user.GH,
                XM: user.XM,
                CJPC: user.CJPC,
                XXID: user.XXID
              });
              this.errorCount = 0;
              window.localStorage.setItem("errorCount", this.errorCount);

              this.$router.push({ path: "/" });
      //
    },
    handleLogin() {
      var that = this;


      this.$refs.loginForm.validate(async valid => {
        if (valid) {
        
          try {   
             showLoading();     
              var school = linq
                .from(this.schools)
                .firstOrDefault(`$.value =='${that.loginForm.XXID}' `);

              that.loginForm.server = school.server;
              var user = await that.$store.dispatch("Login", that.loginForm);
             
              if(user.XM == "管理员"){
                user = {
                ROLE_INPUT: "admin",
                SCHOOL: school.label,
                XXID: school.value,
                CJPC: "2020",
                ROLE_AUDIT: "admin",
                ROLE_VIEW: "admin",
                XM: "管理员",
                TOKEN: user.TOKEN,
                PASSWORD: that.loginForm.password,
                GH: that.loginForm.username
                };
                user.SCHOOL = school.label;
                this.$root.user = user;
                setUser(user);
                

                setSchool(this.loginForm.XXID);
                
              }else{
                user.SCHOOL = school.label;
                 this.$root.user = user;
                 setUser(user);
                 setSchool(this.loginForm.XXID);
                 
                if(user.PASSWORD == "1"){
                  this.resetPasswordDialogVisible = true;
                  return;
                }
              }
            
              await add登录日志({
                ID: uuid.v1(),
                LOGINTIME: new Date().toISOString(),
                GH: user.GH,
                XM: user.XM,
                CJPC: user.CJPC,
                XXID: user.XXID
              });
              this.errorCount = 0;
              window.localStorage.setItem("errorCount", this.errorCount);

              that.$router.push({ path: "/" });
          
          } catch (e) {
            this.refreshCode();
            this.errorCount += 1;
            window.localStorage.setItem("errorCount", this.errorCount);
            
            this.$alert(e);
          } finally {
            hideLoading();
          }
        } else {
          console.log("账号，密码不能为空白");
          return false;
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
$bg: #2d3a4b;
$light_gray: #eee;

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
  .el-select {
    display: inline-block;
    height: 47px;
    width: 85%;
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: $bg;
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 520px;
    max-width: 100%;
    padding: 35px 35px 15px 35px;
    margin: 120px auto;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title {
    font-size: 26px;
    font-weight: 400;
    color: $light_gray;
    margin: 0px auto 40px auto;
    text-align: center;
    font-weight: bold;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
